package com.songtech.auth.role.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.songtech.auth.resource.dao.AuthResMapper;
import com.songtech.auth.resource.model.Resources;
import com.songtech.auth.role.dao.AuthRoleMapper;
import com.songtech.auth.role.model.Role;
import com.songtech.auth.role.service.RoleService;
import com.songtech.auth.role.vo.RoleResourceVo;
import com.songtech.auth.role.vo.RoleUserVo;
import com.songtech.auth.user.model.User;
import com.songtech.auth.util.CommState;
import com.songtech.auth.util.IdGenerator;
import com.songtech.base.exception.BusinessException;
import com.songtech.base.universal.dao.BaseDao;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private AuthRoleMapper authRoleMapper;
	
	@Autowired
	private AuthResMapper resRoleMapper;

	@Resource(name = "com.songtech.auth.role.model.Role")
	private BaseDao<Role> roleDao;
	
	@Override
	public int addRole(Role role) {
		//code为空
		if(StringUtils.isEmpty(role.getCode())){
			return 0;
		}
		if(StringUtils.isEmpty(role.getName())){
			return 0;
		}
		Role qRole = authRoleMapper.queryRoleByRoleCode(role.getCode());
		if(qRole!=null){
			return -1;
		}else{
			role.setId(IdGenerator.UUID());
			role.setState(CommState.EFFECTIVE);
		}
//		authRoleMapper.insert(role);
		try {
			roleDao.insert(role);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new BusinessException("新增角色失败");
		}
		return 1;
	}

	@Override
	public int updateRole(Role role) {
		if(StringUtils.isEmpty(role.getId())){
			return 0;
		}
		Role result = authRoleMapper.queryRoleByRoleId(role.getId());
		if(result==null){
			return -1;
		}else{
			if(!StringUtils.isEmpty(role.getCode())){
				//查看是否已有相同code的角色
				Role resultCode = authRoleMapper.queryRoleByRoleCode(role.getCode());
				//通过新code查询出来的角色ID和当前角色ID不同，则证明已有同样code的角色
				if(resultCode!=null && !(resultCode.getId().equals(role.getId()))){
					return -2;
				}
			}
		}
		try {
			roleDao.updateNotEmpty(role);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		authRoleMapper.update(role);
		return 1;
	}

	@Override
	public int updateRoleByAll(Role role) {
		if(StringUtils.isEmpty(role.getId())){
			return 0;
		}
		Role result = authRoleMapper.queryRoleByRoleId(role.getId());
		if(result==null){
			return -1;
		}else{
			if(!StringUtils.isEmpty(role.getCode())){
				//查看是否已有相同code的角色
				Role resultCode = authRoleMapper.queryRoleByRoleCode(role.getCode());
				//通过新code查询出来的角色ID和当前角色ID不同，则证明已有同样code的角色
				if(resultCode!=null && !(resultCode.getId().equals(role.getId()))){
					return -2;
				}
			}else{
				return 2;
			}
		}
		if(StringUtils.isEmpty(role.getState())){
			role.setState(CommState.INVALID);
		}
		authRoleMapper.updateByAll(role);
		return 1;
	}

	@Override
	public int disabledRole(String roleId) {
		Role result = authRoleMapper.queryRoleByRoleId(roleId);
		if(result==null){
			return 0;
		}
		Role qRole = new Role();
		qRole.setId(roleId);
		qRole.setState(CommState.INVALID);
		authRoleMapper.update(qRole);
		return 1;
	}

	@Override
	public int eabledRole(String roleId) {
		Role result = authRoleMapper.queryRoleByRoleId(roleId);
		if(result==null){
			return 0;
		}
		Role qRole = new Role();
		qRole.setId(roleId);
		qRole.setState(CommState.EFFECTIVE);
		authRoleMapper.update(qRole);
		return 1;
	}

	@Override
	public int deleteRole(String roleId) {
		authRoleMapper.delete(roleId);
		return 1;
	}

	@Override
	public PageInfo<Role> queryRoleAll(Role role,int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<Role> roles = authRoleMapper.queryRoleAll(role);
		return new PageInfo<Role>(roles);
	}

	@Override
	public Role queryRoleByRoleId(String roleId) {
		return authRoleMapper.queryRoleByRoleId(roleId);
	}

	@Override
	public Role queryRoleByRoleCode(String roleCode) {
		return authRoleMapper.queryRoleByRoleCode(roleCode);
	}
	
	@Override
	public List<Role> getRoles(Role role) {
		return authRoleMapper.getRoles(role);
	}

	@Override
	public PageInfo<User> getRoleUsers(String roleId,int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<User> list = authRoleMapper.getRoleUsers(roleId);
		return new PageInfo<User>(list);
	}
	
	@Override
	public List<User> getRoleAllUser(String roleId){
		List<User> list = authRoleMapper.getRoleUsers(roleId);
		return list;
	}
	
	@Override
	public int insertRoleRes(String roleId, List<String> resIdList) {
		//先删除角色已有的资源权限，再新增
		authRoleMapper.deleteResByRoleId(roleId);
		List<RoleResourceVo> voList  = new ArrayList<RoleResourceVo>();
		for(int i=0;i<resIdList.size();i++){
			String roleResId = IdGenerator.UUID();
			if(!StringUtils.isEmpty(resIdList.get(i))){
				RoleResourceVo newVo = new RoleResourceVo(roleResId,roleId,resIdList.get(i));
				voList.add(newVo);
			}
		}
		if(voList.size()>0){
			Map<String, Object> roleResMap = new HashMap<String, Object>();
			roleResMap.put("listRoleResVo", voList);
			authRoleMapper.insertRoleRes(roleResMap);
		}
		return 1;
	}

	@Override
	public List<Resources> getRoleRes(String roleId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("roleId", roleId);
		return resRoleMapper.getRoleRes(map);
	}

	@Override
	public int insertRoleUsers(String roleId, List<String> userIds) {
		//通过角色Id，查询出所有的角色用户关系
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("roleId", roleId);
		List<RoleUserVo> roleUsers = authRoleMapper.queryRoleUserVoByUserIds(map);
		List<String> listOld = new ArrayList<>();
		for(int j=0;j<roleUsers.size();j++){
			String userid=roleUsers.get(j).getUserId();
			listOld.add(userid);
		}
		//如果没有用户，那就删除角色原来关联的用户 关系
		//有用户，就先排除已经存在的关系，新增没有存在的关系，删除已经不存在的关系
		if(userIds.size()>0){
			//找出需要删除的delLists
			List<String> delLists =new ArrayList<String>();
			for (int i = 0; i < listOld.size(); i++) {
				if(!userIds.contains(listOld.get(i))){
					delLists.add(listOld.get(i));
				}
			}
			
			//找出需要新增的insertLists
			List<String> insLists =new ArrayList<String>();
			for (int i = 0; i < userIds.size(); i++) {
				if(!StringUtils.isEmpty(userIds.get(i))){
					if (!listOld.contains(userIds.get(i))){
						insLists.add(userIds.get(i));
					}
				}
			}
			if(insLists.size()>0){
				List<RoleUserVo> roleUserVos = new ArrayList<RoleUserVo>();
				RoleUserVo su=null;
				for(int i=0;i<insLists.size();i++){
					su = new RoleUserVo();
					su.setRoleId(roleId);
					su.setRoleUserId(IdGenerator.UUID());
					su.setUserId(insLists.get(i));
					roleUserVos.add(su);
				}
				Map<String, Object> insVoMaps = new HashMap<String, Object>();
				insVoMaps.put("roleUserVos", roleUserVos);
				authRoleMapper.insertPatchRoleUser(insVoMaps);
			}
			if(delLists.size()>0){
				Map<String, Object> delMaps = new HashMap<String, Object>();
				delMaps.put("userIds", delLists);
				delMaps.put("roleId", roleId);
				authRoleMapper.deletePatchRoleUser(delMaps);
			}
		}else {
			//角色原来用户不为空，删除这些用户 关系
			if(listOld.size()>0){
				Map<String, Object> paramMaps = new HashMap<String, Object>();
				paramMaps.put("userIds", listOld);
				paramMaps.put("roleId", roleId);
				authRoleMapper.deletePatchRoleUser(paramMaps);
			}
		}
		return 1;
	}

	@Override
	public List<Resources> getRes(String loginName) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("loginName",loginName);
		map.put("type","menu");
		return resRoleMapper.getResc(map);
	}

}
